#include <stdio.h>
#include "clock.h"
#include <unistd.h>

static int isLeapYear(int year)
{
	return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}

static int dayOfTheMonth(int year,int month)
{
	int days[] = {31,0,31,30,31,30,31,31,30,31,30,31};
	if(month == 2)
	{
		if(isLeapYear(year))
		{
			return 29;
		}
		else
		{
			return 28;
		}
	}
	else
	{
		return days[month - 1];
	}
}

void showTime(struct DateTime *pdt)
{
	printf("%4d-%02d-%02d %02d:%02d:%02d\r",pdt->year,pdt->month,pdt->day,pdt->hour,pdt->minute,pdt->second);
	fflush(stdout);
}

void incYear(struct DateTime *pdt)
{
	pdt->year += 1;
}

void incMonth(struct DateTime *pdt)
{
	pdt->month += 1; 
	if(pdt->month > 12)
	{
		incYear(pdt);
		pdt->month = 1;
	}
}

void incDay(struct DateTime *pdt)
{
	pdt->day += 1;
	if(pdt->day > dayOfTheMonth(pdt->year,pdt->month))
	{ 
		incMonth(pdt);
		pdt->day = 1;
	}
}

void incHour(struct DateTime *pdt)
{
	pdt->hour += 1;
	if(pdt->hour > 23)
	{
		incDay(pdt);
		pdt->hour = 0;
	}
}

void incMinute(struct DateTime *pdt)
{
	pdt->minute += 1;
	if(pdt->minute > 59)
	{
		incHour(pdt);
		pdt->minute = 0;
	}
}

void incSecond(struct DateTime *pdt)
{
	pdt->second += 1;
	if(pdt->second > 59)
	{
		incMinute(pdt);
		pdt->second = 0;
	}
}

void start(void)
{
	struct DateTime dt = {2021,2,2,20,22,0};
	while(1)
	{
		incSecond(&dt);
		showTime(&dt);
		sleep(1);
	}
}
